package com.zjoin.study.arithmetic.基础.数组;

import com.zjoin.study.arithmetic.基础.ArraysUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 类名 两数之和
 * 描述
 *
 * @Author xwyang
 * @Date 2020/8/20 16:32
 * @Version 1.0
 **/
public class 两数之和 {
    
    /**
     * 给定 nums = [2, 7, 11, 15], target = 9
     * <p>
     * 因为 nums[0] + nums[1] = 2 + 7 = 9
     * 所以返回 [0, 1]
     *
     * @param target
     * @return
     */
    
    public static int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    res[0] = i;
                    res[1] = j;
                }
            }
        }
        return res;
    }
    
    
    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
    
    public static void main(String[] args) {
        int[] s = {1,2,3,8,5};
        ArraysUtil.print(twoSum(s,7));
    }
}
